<template>
  <div class="club-sent-applications">
    <el-table :data="paginatedApplications" style="width: 100%">
      <el-table-column
        prop="typeCode"
        label="申请等级"
        :filters="applicationLevelFilters"
        :filter-method="filterApplicationLevel"
      >
        <template #default="{ row }">
          <span>{{ row.typeCode >= 8 ? "活动" : "社团" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="申请编号" />
      <el-table-column prop="applicantUsername" label="申请人用户名" />
      <el-table-column
        prop="type"
        label="申请类型"
        :filters="applicationTypeFilters"
        :filter-method="filterType"
        filter-placement="bottom-end"
      >
        <template #default="{ row }">
          <el-tag :type="getApplicationTypeColor(row.type)">{{
            row.type
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="clubName" label="社团名" />
      <el-table-column prop="activityName" label="活动名" />
      <el-table-column
        prop="status"
        label="申请状态"
        :filters="statusFilters"
        :filter-method="filterStatus"
        filter-placement="bottom-end"
      >
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="applyTime" label="申请时间" sortable>
        <template #header>
          <span>申请时间</span>
          <el-button type="text" @click="sortByApplyTime">
            <el-icon>
              <sort v-if="sortOrder === 'descending'" />
              <sort-up v-else />
            </el-icon>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleDetails(row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:currentPage="currentPage"
        :page-size="pageSize"
        :total="totalApplications"
        layout="total, prev, pager, next"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import {
  ActivityApplicationControllerService,
  type ActivityApplicationVO,
  ClubApplicationControllerService,
  type ClubApplicationQueryRequest,
} from "../../../../generated";
import { useUserStore } from "../../../stores/user.ts";

interface SentApplication {
  id: number;
  applicantUsername: string;
  typeCode: number;
  type: string;
  clubId: number;
  clubName: string;
  activityId: number;
  activityName: string;
  status: string;
  applyTime: string;
}

const applications = ref<SentApplication[]>([]);

// 获取状态对应的标签类型
const getStatusType = (status: string) => {
  switch (status) {
    case "待审核":
      return "warning";
    case "通过":
      return "success";
    case "拒绝":
      return "danger";
    default:
      return "info";
  }
};

const getApplicationType = (type: number): string => {
  switch (type) {
    case 5:
      return "创建社团";
    case 6:
      return "注销社团";
    case 7:
      return "修改社团信息";
    case 8:
      return "举办活动";
    case 9:
      return "取消活动";
    case 10:
      return "修改活动信息";
    default:
      return "";
  }
};

const getApplicationTypeColor = (type: string): string => {
  switch (type) {
    case "注销社团":
    case "取消活动":
      return "danger";
    case "创建社团":
    case "举办活动":
      return "success";
    case "修改社团信息":
    case "修改活动信息":
      return "primary";
    default:
      return "info";
  }
};

const getActivityName = (application: ActivityApplicationVO): string => {
  if (application.type === 8) {
    return application.additionalInfo?.activityName as string;
  } else {
    return application.activityVO?.activityName as string;
  }
};

const userStore = useUserStore();
const loadData = async () => {
  try {
    const clubApplicationRes =
      await ClubApplicationControllerService.listClubApplicationVoByPage({
        clubId: userStore.managedClubId,
      } as ClubApplicationQueryRequest);

    if (clubApplicationRes.code === 0) {
      const clubApplicationVoList = clubApplicationRes.data?.records;
      applications.value = clubApplicationVoList?.map(
        (application) =>
          ({
            id: application.id,
            applicantUsername: application.userVo?.userName,
            typeCode: application.type,
            type: getApplicationType(application.type as number),
            clubId: application.clubVo?.id,
            clubName: application.clubVo?.clubName,
            status: application.reviewVO?.result,
            applyTime: application.createTime,
          }) as SentApplication,
      );
    } else {
      ElMessage.error("加载数据时发生错误：" + clubApplicationRes.message);
    }

    const activityApplicationRes =
      await ActivityApplicationControllerService.listApplicationVoByPage1({});

    if (activityApplicationRes.code === 0) {
      const activityApplicationVoList = activityApplicationRes.data
        ?.records as ActivityApplicationVO[];
      for (const application of activityApplicationVoList) {
        applications.value.push({
          id: application.id,
          applicantUsername: application.userVO?.userName,
          typeCode: application.type,
          type: getApplicationType(application.type as number),
          clubId: application.activityVO?.clubVO?.id,
          clubName: application.activityVO?.clubVO?.clubName,
          activityId: application,
          activityName: getActivityName(application),
          status: application.reviewVO?.result,
          applyTime: application.createTime,
        } as SentApplication);
      }
    } else {
      ElMessage.error("加载数据时发生错误：" + activityApplicationRes.message);
    }
  } catch (error) {
    console.error("加载数据时发生错误:", error);
    ElMessage.error("加载数据时发生错误，请稍后重试");
  }
};

onMounted(() => {
  loadData();
});

// 定义申请类型筛选选项
const applicationTypeFilters = [
  { text: "创建社团", value: "创建社团" },
  { text: "注销社团", value: "注销社团" },
  { text: "修改社团信息", value: "修改社团信息" },
  { text: "举办活动", value: "举办活动" },
  { text: "取消活动", value: "取消活动" },
  { text: "修改活动信息", value: "修改活动信息" },
];

// 筛选申请类型方法
const filterType = (value: string, row: SentApplication) => {
  return row.type === value;
};

// 定义状态筛选选项
const statusFilters = [
  { text: "待审核", value: "待审核" },
  { text: "通过", value: "通过" },
  { text: "拒绝", value: "拒绝" },
];

// 筛选审核状态方法
const filterStatus = (value: string, row: SentApplication) => {
  return row.status === value;
};

// 申请等级筛选项
const applicationLevelFilters = [
  { text: "社团", value: "社团" },
  { text: "活动", value: "活动" },
];

// 筛选申请等级方法
const filterApplicationLevel = (value: string, row: SentApplication) => {
  return (row.typeCode >= 8 ? "活动" : "社团") === value;
};

// 按申请时间排序
const sortOrder = ref("descending");

const sortByApplyTime = () => {
  applications.value.sort((a, b) => {
    const timeA = new Date(a.applyTime).getTime();
    const timeB = new Date(b.applyTime).getTime();
    return sortOrder.value === "ascending" ? timeA - timeB : timeB - timeA;
  });
  sortOrder.value =
    sortOrder.value === "ascending" ? "descending" : "ascending";
};

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const totalApplications = computed(() => applications.value.length);

const paginatedApplications = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return applications.value.slice(startIndex, endIndex);
});

const handlePageChange = (page: number) => {
  currentPage.value = page;
};

const router = useRouter();
// 处理详情按钮点击事件
const handleDetails = (row: SentApplication) => {
  const routePath =
    row.typeCode >= 8
      ? "/manager/application/activity/info"
      : "/manager/application/club/info";
  router.push({
    path: routePath,
    query: { id: row.id },
  });
};
</script>

<style scoped>
.club-sent-applications {
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
